package com.xzw;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

//过滤器中的/xzw/* 指的是拦截 /xzw 下所有的资源
//在本项目中，仅需一个过滤器即可，即拦截/* 下所有的资源
@WebFilter(urlPatterns = "/xzw/*")
public class CoreFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //初始化
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        //将req强制类型转化为HttpServletRequest对象
        HttpServletRequest request=(HttpServletRequest) req;
        //将resp强制类型转化为HttpServletResponse对象
        HttpServletResponse response=(HttpServletResponse) resp;

        String uri = request.getRequestURI();
        if("/xzw/login.jsp".equals(uri) || uri.endsWith(".css")){
            //此时被拦截的是登录页，允许通过
            chain.doFilter(req, resp);
            return;
        }

        //获取session
        HttpSession session = request.getSession();
        Object uid = session.getAttribute("UID");
        if(uid == null){
            //说明用户没有登陆
            response.sendRedirect("/xzw/login.jsp");
            return;
        }
        //说明用户已经登陆过,允许通过
        chain.doFilter(req, resp);
    }

    @Override
    public void destroy() {
        //析构函数，当过滤器被销毁的时候被执行

    }
}
